package com.cook.service.impl;

import com.cook.service.EmailLoginService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class EmailLoginServiceImpl implements EmailLoginService {

    private final JavaMailSender mailSender;
    private final RedisTemplate<String, String> redisTemplate;

    public void sendVerificationCode(String email) {
        // 1. 生成6位验证码
        String code = RandomStringUtils.randomNumeric(6);

        // 2. 存储到Redis（5分钟过期）
        redisTemplate.opsForValue().set(
                "email:code:" + email,
                code,
                5, TimeUnit.MINUTES
        );

        // 3. 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("3125604733@qq.com");
        message.setTo(email);
        message.setSubject("您的登录验证码");
        message.setText("验证码：" + code + "，5分钟内有效");
        mailSender.send(message);
    }
}
